//=============================================================================
// Scene_Item.Window_ItemList
//=============================================================================
const originItemListInit = Window_ItemList.prototype.initialize;
Window_ItemList.prototype.initialize = function (x, y, width, height) {
    originItemListInit.call(this, x, y, width, height);
    this._backgroundSprite = new Sprite();
    this._backgroundSprite.bitmap =
        ImageManager.loadBitmap('img/system/UI/', 'MenuBg_List');
    this.addChildAt(this._backgroundSprite, 0);
    this._backgroundSprite.x = -17;
    this._backgroundSprite.y = -1;
};


// changeWindowWidth
Window_ItemList.prototype.windowWidth = function () {
    return 128;
};

// select
const originSelect = Window_ItemList.prototype.select
Window_ItemList.prototype.select = function (index) {
    originSelect.call(this, index)
    this.$emit('select', ...arguments)
}

// deselect
const originDeSelect = Window_ItemList.prototype.deselect
Window_ItemList.prototype.deselect = function () {
    originDeSelect.call(this)
    this.$emit('deselect', ...arguments)
}
/*
const isCurrentItemEnabled = Window_ItemList.prototype.isCurrentItemEnabled
Window_ItemList.prototype.isCurrentItemEnabled = function () {
    if (!$gameParty.canUse(this.item())) return false

    return isCurrentItemEnabled.call(this)
}
*/
const originRefresh = Window_ItemList.prototype.refresh
Window_ItemList.prototype.refresh = function() {
    originRefresh.call(this);
    this.showView();
    this.showPetInfo()
    this.callUpdateHelp();
};


Window_ItemList.prototype.drawIcon = function (iconIndex, x, y, alpha = 255) {
    const bitmap = ImageManager.loadSystem('IconSet');
    const pw = Window_Base._iconWidth;
    const ph = Window_Base._iconHeight;
    const sx = iconIndex % 16 * pw;
    const sy = Math.floor(iconIndex / 16) * ph;

    // 应用带透明度的icon
    const opacityBitmap = bitmap.clone(bit => bit.paintOpacity = alpha)
    this.contents.blt(opacityBitmap, sx, sy, pw, ph, x, y)
}

// 老饕：覆写可用状态（YEP默认物品全都可以使用）
Window_ItemList.prototype.isEnabled = function (item) {
    if (!item) return false;
    return Yanfly.Item.Window_ItemList_isEnabled.call(this, item);
};

// 不可用项以红色显示（老饕：因此方法影响装备窗口绘制，故将可用条件判定方法修改为isEnabled，可通用）
Window_ItemList.prototype.drawItemName = function (item, x, y, width) {
    width = width || 312
    if (item) {
        const iconBoxWidth = Window_Base._iconWidth + 4;
        this.resetTextColor();
        //if (!$gameParty.canUse(item)) {
        if (!this.isEnabled(item)){
            this.changeTextColor(this.hpGaugeColor1());
            this.drawIcon(this.realItem(item).iconIndex, x + 2, y + 2, 125);//alpha=125
        } else {
            this.drawIcon(this.realItem(item).iconIndex, x + 2, y + 2);
        }
        this.drawText(item.name.split("（")[0], x + iconBoxWidth, y, width - iconBoxWidth);
        this.drawItemLevel(item, x, y, width - iconBoxWidth);
    }
}

Window_ItemList.prototype.realItem = function(item) {
    if($gameParty.inBattle()){
        if(CP.UseEquipManager.isEquipUsable(item))
                item = CP.UseEquipManager.getRealUseItem(item);
    }else if(!!this._ext){
        if(this._ext == '恢复' || this._ext == '攻击' || this._ext == '辅助'){
            if(CP.UseEquipManager.isEquipUsable(item))
                item = CP.UseEquipManager.getRealUseItem(item);
        }
    }
    return item;
};
// 补充类型
const originItemListIncludes = Window_ItemList.prototype.includes;
Window_ItemList.prototype.includes = function(item) {
    switch (this._category) {
    case 'equips':
        return (DataManager.isWeapon(item) || DataManager.isArmor(item)) && !item.itemCategory.contains('护驾');
    default:
        return originItemListIncludes.call(this, item);
    }
}

// 
Window_ItemList.prototype.drawItemLevel = function(item, dx, dy, dw) {
    let level = 0;
    if (this._ext == '护驾') {
        level = item.catchLevel;
        if (item.useItemId){
            if($dataItems[item.useItemId].petAddedInfo){
                level = $dataEnemies[$dataItems[item.useItemId].petAddedInfo.enemyId].catchLevel;
            }
        }
        this.setSmallerFont();
        this.contents.fontSize = Yanfly.Param.ItemQuantitySize;
        this.drawText(level + TextManager.levelA, dx, dy, dw, 'right');
        this.resetFontSettings();
    }
};

// 物品列表排序
const originItemListMakeItemList = Window_ItemList.prototype.makeItemList;
Window_ItemList.prototype.makeItemList = function() {
    originItemListMakeItemList.call(this);
    // 物品排序
    this._data.sort(function (a, b) {
        if (!a || !b)
            return
        // 护驾按等级或种族排序
        if (a.itemCategory.contains('护驾') && a.itemCategory.contains('护驾')) {
            if (!a.enemyId || !b.enemyId)
                return
            if ($dataEnemies[a.enemyId] == undefined || $dataEnemies[b.enemyId] == undefined)
                return
            if (ConfigManager['enemySort']) {
                // 等级优先排序
                if (!$dataEnemies[a.enemyId].catchLevel || !$dataEnemies[b.enemyId].catchLevel)
                    return
                if ($dataEnemies[b.enemyId].catchLevel - $dataEnemies[a.enemyId].catchLevel !== 0) {
                    return $dataEnemies[b.enemyId].catchLevel - $dataEnemies[a.enemyId].catchLevel
                } else {
                    if (!$dataEnemies[a.enemyId].classId || !$dataEnemies[b.enemyId].classId)
                        return
                    return $dataEnemies[a.enemyId].classId - $dataEnemies[b.enemyId].classId
                }
            } else {
                // 种族优先排序
                if (!$dataEnemies[a.enemyId].classId || !$dataEnemies[b.enemyId].classId)
                    return
                if ($dataEnemies[a.enemyId].classId - $dataEnemies[b.enemyId].classId !== 0) {
                    return $dataEnemies[a.enemyId].classId - $dataEnemies[b.enemyId].classId

                } else {
                    if (!$dataEnemies[a.enemyId].catchLevel || !$dataEnemies[b.enemyId].catchLevel)
                        return
                    return $dataEnemies[b.enemyId].catchLevel - $dataEnemies[a.enemyId].catchLevel
                }
            }
        // 非护驾则按图标编号排序
        }else{
            a = CP.UseEquipManager.getRealUseItem(a);
            b = CP.UseEquipManager.getRealUseItem(b);
            if (!a || !b)
                return
            return DataManager.itemSortMapping(a.iconIndex) - DataManager.itemSortMapping(b.iconIndex)
        }
    });

};